﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace MPic.Utility
{
    public static class EnumHelper
    {

        /// <summary>
        /// 返回枚举的值
        /// </summary>
        /// <param name="enum"></param>
        /// <returns></returns>
        public static int ToInt(this object @enum)
        {
            if (@enum == null)
                return 0;
            return (int)@enum;
        }


        /// <summary>
        /// 从枚举中获取Description
        /// </summary>
        /// <param name="enum">需要获取枚举描述的枚举</param>
        /// <returns>描述内容</returns>
        public static string Description(this object @enum)
        {
            string _description = string.Empty;
            FieldInfo _fieldInfo = @enum.GetType().GetField(@enum.ToString());
            DescriptionAttribute[] _attributes = _fieldInfo.GetDescriptAttr();
            if (_attributes != null && _attributes.Length > 0)
                _description = _attributes[0].Description;
            else
                _description = @enum.ToString();
            return _description;
        }

        public static DescriptionAttribute[] GetDescriptAttr(this FieldInfo fieldInfo)
        {
            if (fieldInfo != null)
            {
                return (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
            }
            return null;
        }
    }
}
